package reflex.learning02;

import org.junit.Test;

import java.lang.reflect.Constructor;

/**
 * @program JavaBase
 * @description:
 * @author: zhanglu
 * @create: 2019-06-07 22:24:00
 */
public class TestConstructor {

    @Test
    public void test01() throws Exception{
        String classname = "reflex.learning02.Person";
        Class clazz = Class.forName(classname);
        /**
         * 创建对应的运行时类的对象。使用newInstance，实际上
         * 是调用了运行时类的无参构造器
         * 要想能够创建成功，
         *  - 要求对应的运行时类要有无参的构造器
         *  - 构造器的权限修饰符的权限要足够
         */
        Object obj = clazz.newInstance();
        Person p = (Person) obj;
    }

    @Test
    public void test02(){
        Class clazz = Person.class;
        Constructor[] constructors = clazz.getDeclaredConstructors();
        for(Constructor c : constructors){
            System.out.println(c);
        }
    }

    /**
     * 调用指定构造器
     */
    @Test
    public void test03() throws Exception{
        Class clazz = Person.class;
        Constructor constructor = clazz.getDeclaredConstructor(String.class, Integer.class);
        constructor.setAccessible(true);
        Person p = (Person) constructor.newInstance("张三", 22);
        System.out.println(p);
    }
}
